﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Web;

namespace WeiXinUtils
{
    public enum WeiXinAuthScope
    {
        snsapi_base=0,
        snsapi_userinfo=1
    }

    public class WeiXinOAuth2:WeiXinBase
    {
        private HttpContext m_Context;
        private WeiXinAuthScope m_Scope;
        public WeiXinOAuth2(string Appid, string Secret, WeiXinAuthScope Scope)
            : base(Appid, Secret)
        {
            m_Context = System.Web.HttpContext.Current;
            m_Scope = Scope;
        }

        public static WeiXinOAuthResult GetOAuth2(string Appid, string Secret, WeiXinAuthScope Scope)
        {
            WeiXinOAuth2 auth = new WeiXinOAuth2(Appid, Secret, Scope);
            return auth.Execute();
        }

        private WeiXinOAuthResult Execute()
        {
            if (!m_Context.Request.UserAgent.ToLower().Contains("micromessenger"))
            {
                //WeiXinOAuthResult result = new WeiXinOAuthResult();
                //result.openid = "12345678";
                //return result;
                return null;
            }

            string weixinCode = m_Context.Request.Params["code"];
            if (!string.IsNullOrEmpty(weixinCode))
            {
                return GetWeiXinUserInfoByCode(weixinCode);
            }
            else
            {
                OAuth2();
            }

            return null;
        }

        private void OAuth2()
        {
            Regex r = new Regex(":[0-9]+/");
            string redictUrl = m_Context.Request.Url.ToString();
            redictUrl = r.Replace(redictUrl,"/");
            string requestUrl = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state=0#wechat_redirect", this.appid, HttpUtility.UrlEncode(redictUrl), m_Scope.ToString());
            m_Context.Response.Redirect(requestUrl);
        }

        public WeiXinOAuthResult GetWeiXinUserInfoByCode(string Code)
        {
            WeiXinOAuthResult result = new WeiXinOAuthResult();
            string requestUrl = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code ",this.appid,this.secret,Code);
            dynamic returnData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(HttpsUtils.Get(requestUrl));
            result.openid = returnData.openid;
            string getInfoToken = returnData.access_token;
            if (m_Scope == WeiXinAuthScope.snsapi_base)
            {
                return result ;
            }

            requestUrl = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN ", getInfoToken, result.openid);
            dynamic userData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(HttpsUtils.Get(requestUrl));
            result.city = userData.city;
            result.country = userData.country;
            result.headimgurl = userData.headimgurl;
            result.nickname = userData.nickname;
            result.privilege = userData.privilege;
            result.province = userData.province;
            result.sex = userData.sex;
            result.unionid = userData.unionid;
            return result;
        }
 
    }
}